package com.hls.modules.sysjob.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hls.core.entity.R;
import com.hls.modules.sysjob.entity.SysJob;
import com.hls.modules.sysjob.service.impl.SysJobServiceImpl;
import com.hls.modules.sysjob.util.ScheduleConstants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 调度任务信息操作处理
 * 
 */
@Controller
@RequestMapping("/sysjob")
public class SysJobController {

    @Resource
    private SysJobServiceImpl sysJobService;

    @GetMapping("")
    public ModelAndView page(Page page, SysJob sysJob)
    {
        ModelAndView modelAndView = new ModelAndView();
		QueryWrapper<SysJob> queryWrapper = new QueryWrapper<>();
        modelAndView.addObject("jobList", sysJobService.page(page, queryWrapper).getRecords());
        modelAndView.setViewName("sysjob");
        return modelAndView;
    }

    public R<Object> delete(String[]  ids){
        sysJobService.deleteJobByIds(ids);
        return R.ok();
    }

	@DeleteMapping("/{id}")
	public R<Object> removeById(@PathVariable String id){
		return R.ok(sysJobService.removeById(id));
	}

	@DeleteMapping("/remove")
	public R<Object> remove(@RequestBody Map<String, String> param)
	{
		String ids = param.getOrDefault("ids", "");
		return this.delete(StringUtils.split(ids, ","));
	}

    /**
     * 任务调度状态修改
     */
    @ResponseBody
    @PostMapping("/changeStatus")
    public R<Object> changeStatus(@RequestBody SysJob job)
    {
        String msg = "任务" + (ScheduleConstants.Status.NORMAL.getValue().equals(job.getStatus())?"启用":"停用") + "成功！";
        return R.ok(sysJobService.changeStatus(job), msg);
    }

    /**
     * 任务调度立即执行一次
     */
    @ResponseBody
    @PostMapping("/run/{jobId}")
    public R<Object> run(@PathVariable String jobId)
    {
        return R.ok(sysJobService.run(jobId));
    }

    /**
     * 新增保存调度
     */
    @PostMapping("/add")
    public R<Object> addSave(@RequestBody SysJob job)
    {
        return R.ok(sysJobService.save(job));
    }

    /**
     * 修改保存调度
     */
    @PutMapping("/edit")
    public R<Object> editSave(@RequestBody SysJob job)
    {
        return R.ok(sysJobService.updateJobCron(job));
    }
    
    /**
     * 校验cron表达式是否有效
     */
    @GetMapping("/checkCronExpressionIsValid")
    public boolean checkCronExpressionIsValid(@RequestParam String cronExpression)
    {
        return sysJobService.checkCronExpressionIsValid(cronExpression);
    }
}